package com.pubinfo.passbook.engine.chain.transfer;

import com.pubinfo.passbook.engine.chain.ComputeChain;

import java.util.Collection;
import java.util.concurrent.atomic.AtomicReference;

/**
 * 循环计算链转化器
 * <p>
 * 重写了compute方法, 废弃了convert方法, 改为使用convertToCollection方法进行数据转化.
 *
 * @param <S>
 * @param <T>
 * @param <R>
 */
public abstract class ComputeLoopChainTransfer<T, S, R> extends ComputeChainTransfer<T, S, R> {

    public ComputeLoopChainTransfer(ComputeChain<S, R> computor) {
        super(computor);
    }

    /**
     * 循环计算链执行
     *
     * @param data
     * @param beforeVal
     * @return
     */
    @Override
    public R compute(T data, R beforeVal) {
        AtomicReference<R> result = new AtomicReference<>(beforeVal);
        realComputeChain.setCache(cache);
        for (S subData : convertToCollection(data)) {
            result.set(realComputeChain.compute(subData, result.get()));
        }
        return result.get();
    }

    @Deprecated
    @Override
    S convert(T data) {
        throw new RuntimeException("循环计算链转化器请勿调用convert方法");
    }

    /**
     * 循环计算链需要多种计算
     *
     * @param data
     * @return
     */
    abstract Collection<S> convertToCollection(T data);
}